#!/usr/bin/python3
'''
这里面是一些辅助用的加解密函数
'''
from Crypto.Hash import SHA256
import os
import random
from umbral import *

def cloud_sha256(text):
    if isinstance(text, str): 
        return SHA256.new(text.encode('utf-8')).hexdigest()
    else:
        raise TypeError

# def cloud_aes_encrypt(plaintext):
#     '''
#     封装aes算法，使用CBC加密模式。为了不让算法写得不太好看，输入和输出一律位bytes型。
#     一律不要iv（128位和AES的分组长度一致）和key（自动生成128位），填充方式使用默认的pkcs#7
#     '''
#     key = get_random_bytes(16)
#     cipher = AES.new(key, AES.MODE_CBC)
#     ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
#     return ciphertext, key, cipher.iv

# def cloud_aes_decrypt(ciphertext, key, iv):
#     '''
#     与cloud_aes_encrypt配对，需要提供key和iv
#     '''
#     cipher = AES.new(key, AES.MODE_CBC, iv)
#     plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
#     return plaintext

def cloud_pre_genkey(path):
    '''
    generate a delegating key pair and a signing key pair，并写入到path，其中私钥32，公钥33
    '''
    # delegating key pair
    secret_key = SecretKey.random()
    public_key = secret_key.public_key()

    # signing key pair
    signing_key = SecretKey.random()
    verifying_key = signing_key.public_key()

    # 写入到'./key/'，其中私钥32，公钥33
    dkey = secret_key.to_secret_bytes()+public_key.__bytes__()
    with open(path+'/delegating_key.txt', 'wb') as f:
        f.write(dkey)

    skey = signing_key.to_secret_bytes()+verifying_key.__bytes__()
    with open(path+'/signing_key.txt', 'wb') as f:
        f.write(skey)  

    return secret_key, public_key, signing_key, verifying_key

def cloud_pre_restore_delegatingkeypair(path):
    '''
    读取文件中的签名密钥bytes还原签名密钥对
    '''
    with open(path+'/delegating_key.txt', 'rb') as f:
        secret_key_bytes = f.read(32)
        public_key_bytes = f.read(33)
    secret_key = SecretKey._from_exact_bytes(secret_key_bytes)
    public_key = PublicKey._from_exact_bytes(public_key_bytes)
    return secret_key, public_key

def cloud_pre_restore_signingkeypair(path):
    '''
    读取文件中的签名密钥bytes还原签名密钥对
    '''
    with open(path+'/signing_key.txt', 'rb') as f:
        signing_key_bytes = f.read(32)
        verifying_key_bytes = f.read(33)
    signing_key = SecretKey._from_exact_bytes(signing_key_bytes)
    verifying_key = PublicKey._from_exact_bytes(verifying_key_bytes)
    return signing_key, verifying_key



